package com.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.DB;

import com.google.gson.Gson;
import com.service.Impl.UserServiceImpl;
import com.vo.Uservo;

public class UserServlet extends HttpServlet {

	
	public void destroy() {
		super.destroy();
	}

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			this.doPost(request, response);
		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String action=request.getParameter("action");
		if ("addInfo".equals(action)) {
			String uname=request.getParameter("uname");
			String pswd=request.getParameter("pswd");
			Uservo vo=new Uservo();
			vo.setUname(uname);
			vo.setPswd(pswd);
			int r=userServiceImpl.userNameAsSame(db, uname);//-1 0 1 2
			if (r==-1) {
				
				out.print("-1");   //查询过程中出错了,客户端应该提示查询出错
			} else if(r==0){
				
				userServiceImpl.userAdd(db, vo);
				out.print("1");		//当前用户名没有重复的,可以正常使用
				
			}else if(r>0){
				
				out.print("2");		//当前用户名已存在,客户端应该提示重复不可使用
			}
			
		}else if("login".equals(action)){
			
			String uname=request.getParameter("uname");
			String pswd=request.getParameter("pswd");
			Uservo vo=new Uservo();
			vo.setUname(uname);
			vo.setPswd(pswd);
			int r=userServiceImpl.userLogin(db, vo);
			out.print(r);
			
		}else if ("findone".equals(action)) {
			
			String uname=request.getParameter("uname");
			Uservo vo=userServiceImpl.userFindByUname(db, uname);
			Gson gson=new Gson();
			String s=gson.toJson(vo);
			out.println(s);
			
		} else if("showall".equals(action)){

			List<Uservo> list=userServiceImpl.userShowAll(db);
			Gson gson=new Gson();
			String s=gson.toJson(list);
			System.out.println(s);
			out.print(s);
			
		}
		
		out.flush();
		out.close();
	}

	
	public void init() throws ServletException {
	userServiceImpl=new UserServiceImpl();
	db=new DB();
	}
private UserServiceImpl userServiceImpl=null;
private DB db=null;
}
